<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/png" href="/logo.png">
    <title>Sageflow</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
            background-color: #ffffff;
            color: #374151;
            line-height: 1.6;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* 头部 */
        .header {
            background: #ffffff;
            border-bottom: 1px solid #e5e7eb;
            padding: 1rem;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .header h1 {
            font-size: 1.5rem;
            font-weight: 600;
            color: #111827;
            margin-bottom: 0.5rem;
        }

        .header p {
            color: #6b7280;
            font-size: 0.875rem;
        }

        /* 主要内容区域 */
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        /* 标签页 */
        .tabs {
            display: flex;
            background: #f9fafb;
            border-bottom: 1px solid #e5e7eb;
        }

        .tab {
            flex: 1;
            padding: 0.75rem 1rem;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 0.875rem;
            font-weight: 500;
            color: #6b7280;
            transition: all 0.2s;
        }

        .tab.active {
            background: #ffffff;
            color: #111827;
            border-bottom: 2px solid #3b82f6;
        }

        .tab:hover {
            background: #f3f4f6;
        }

        /* 标签页内容 */
        .tab-content {
            display: none;
            flex: 1;
            flex-direction: column;
            overflow: hidden;
        }

        .tab-content.active {
            display: flex;
        }

        /* 文件上传区域 */
        .upload-section {
            padding: 2rem;
            text-align: center;
        }

        .upload-area {
            border: 2px dashed #d1d5db;
            border-radius: 0.5rem;
            padding: 3rem 2rem;
            margin-bottom: 1.5rem;
            transition: all 0.2s;
            cursor: pointer;
        }

        .upload-area:hover {
            border-color: #3b82f6;
            background: #f8fafc;
        }

        .upload-area.dragover {
            border-color: #3b82f6;
            background: #eff6ff;
        }

        .upload-icon {
            font-size: 3rem;
            color: #9ca3af;
            margin-bottom: 1rem;
        }

        .upload-text {
            color: #6b7280;
            margin-bottom: 1rem;
        }

        .file-input {
            display: none;
        }

        .btn {
            background: #3b82f6;
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            cursor: pointer;
            font-size: 0.875rem;
            font-weight: 500;
            transition: all 0.2s;
        }

        .btn:hover {
            background: #2563eb;
        }

        .btn:disabled {
            background: #9ca3af;
            cursor: not-allowed;
        }

        .btn-secondary {
            background: #f3f4f6;
            color: #374151;
        }

        .btn-secondary:hover {
            background: #e5e7eb;
        }

        /* URL 导入 */
        .url-import {
            margin-top: 2rem;
            padding-top: 2rem;
            border-top: 1px solid #e5e7eb;
        }

        .input-group {
            display: flex;
            gap: 0.5rem;
            margin-top: 1rem;
        }

        .input {
            flex: 1;
            padding: 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 0.5rem;
            font-size: 0.875rem;
        }

        .input:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        /* 聊天区域 */
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 1rem;
            background: #ffffff;
        }

        .message {
            margin-bottom: 1.5rem;
            max-width: 100%;
        }

        .message-user {
            display: flex;
            justify-content: flex-end;
        }

        .message-ai {
            display: flex;
            justify-content: flex-start;
        }

        .message-content {
            max-width: 80%;
            padding: 0.75rem 1rem;
            border-radius: 1rem;
            font-size: 0.875rem;
            line-height: 1.5;
        }

        .message-user .message-content {
            background: #3b82f6;
            color: white;
            border-bottom-right-radius: 0.25rem;
        }

        .message-ai .message-content {
            background: #f3f4f6;
            color: #374151;
            border-bottom-left-radius: 0.25rem;
        }

        .message-ai .message-content pre {
            background: #1f2937;
            color: #f9fafb;
            padding: 0.75rem;
            border-radius: 0.5rem;
            overflow-x: auto;
            margin: 0.5rem 0;
            font-size: 0.8rem;
        }

        /* 输入区域 */
        .chat-input {
            border-top: 1px solid #e5e7eb;
            padding: 1rem;
            background: #ffffff;
        }

        .input-container {
            display: flex;
            gap: 0.5rem;
            align-items: flex-end;
        }

        .message-input {
            flex: 1;
            min-height: 2.5rem;
            max-height: 8rem;
            padding: 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 1.5rem;
            resize: none;
            font-size: 0.875rem;
            font-family: inherit;
        }

        .message-input:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        .send-btn {
            width: 2.5rem;
            height: 2.5rem;
            border-radius: 50%;
            background: #3b82f6;
            color: white;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }

        .send-btn:hover {
            background: #2563eb;
        }

        .send-btn:disabled {
            background: #9ca3af;
            cursor: not-allowed;
        }

        /* 状态提示 */
        .status {
            padding: 0.75rem 1rem;
            margin: 1rem;
            border-radius: 0.5rem;
            font-size: 0.875rem;
        }

        .status-success {
            background: #d1fae5;
            color: #065f46;
            border: 1px solid #a7f3d0;
        }

        .status-error {
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fca5a5;
        }

        .status-info {
            background: #dbeafe;
            color: #1e40af;
            border: 1px solid #93c5fd;
        }

        /* 加载动画 */
        .loading {
            display: inline-block;
            width: 1rem;
            height: 1rem;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #3b82f6;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                height: 100vh;
            }

            .header {
                padding: 0.75rem;
            }

            .header h1 {
                font-size: 1.25rem;
            }

            .upload-section {
                padding: 1rem;
            }

            .upload-area {
                padding: 2rem 1rem;
            }

            .message-content {
                max-width: 90%;
            }

            .chat-input {
                padding: 0.75rem;
            }

            .tabs {
                overflow-x: auto;
            }

            .tab {
                white-space: nowrap;
                min-width: 120px;
            }
        }

        /* 隐藏类 */
        .hidden {
            display: none !important;
        }

        /* 文档列表 */
        .document-list {
            padding: 1rem;
        }

        .document-item {
            background: #f9fafb;
            border: 1px solid #e5e7eb;
            border-radius: 0.5rem;
            padding: 1rem;
            margin-bottom: 0.75rem;
        }

        .document-item.active {
            border-color: #3b82f6;
            background: #eff6ff;
        }

        .document-title {
            font-weight: 600;
            color: #111827;
            margin-bottom: 0.25rem;
        }

        .document-meta {
            font-size: 0.75rem;
            color: #6b7280;
        }
    </style>
</head>
<body>
<div class="container">
    <!-- 头部 -->
    <div class="header">
        <h1>Sageflow</h1>
        <p>大模型驱动的智能接口测试平台</p>
    </div>

    <!-- 主要内容 -->
    <div class="main-content">
        <!-- 标签页导航 -->
        <div class="tabs">
            <button class="tab active" onclick="switchTab('upload')">📄 文档上传</button>
            <button class="tab" onclick="switchTab('chat')">💬 智能对话</button>
            <button class="tab" onclick="switchTab('docs')">📚 文档管理</button>
        </div>

        <!-- 文档上传标签页 -->
        <div id="upload-tab" class="tab-content active">
            <div class="upload-section">
                <div class="upload-area" onclick="document.getElementById('fileInput').click()"
                     ondrop="handleDrop(event)" ondragover="handleDragOver(event)" ondragleave="handleDragLeave(event)">
                    <div class="upload-icon">📁</div>
                    <div class="upload-text">
                        <strong>点击上传或拖拽文件到此处</strong><br>
                        支持 JSON、YAML 格式的 OpenAPI/Swagger 文档
                    </div>
                    <input type="file" id="fileInput" class="file-input" accept=".json,.yaml,.yml,.txt"
                           onchange="handleFileSelect(event)">
                    <button class="btn">选择文件</button>
                </div>

                <div class="url-import">
                    <h3>或从 URL 导入文档</h3>
                    <div class="input-group">
                        <input type="url" id="urlInput" class="input" placeholder="输入 OpenAPI 文档的 URL 地址">
                        <button class="btn" onclick="importFromUrl()">导入</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 智能对话标签页 -->
        <div id="chat-tab" class="tab-content">
            <div class="chat-container">
                <div class="chat-messages" id="chatMessages">
                    <div class="message message-ai">
                        <div class="message-content">
                            👋 你好！我是你的 API 测试助手。<br><br>
                            我可以帮助你：<br>
                            • 📄 管理 OpenAPI/Swagger 文档<br>
                            • 🔧 设置固定参数（如 API Key）<br>
                            • 🚀 执行接口测试<br>
                            • 📊 分析测试结果<br><br>
                            请先上传你的 API 文档，然后告诉我你想要测试什么！
                        </div>
                    </div>
                </div>
                <div class="chat-input">
                    <div class="input-container">
                            <textarea id="messageInput" class="message-input" placeholder="输入你的消息..."
                                      onkeydown="handleKeyDown(event)" rows="1"></textarea>
                        <button id="sendBtn" class="send-btn" onclick="sendMessage()">
                            <span id="sendIcon">➤</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 文档管理标签页 -->
        <div id="docs-tab" class="tab-content">
            <div class="document-list" id="documentList">
                <div class="status status-info">
                    正在加载文档列表...
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 全局变量
    let isLoading = false;
    const API_BASE = '';

    // 标签页切换
    function switchTab(tabName) {
        // 隐藏所有标签页内容
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });

        // 移除所有标签的激活状态
        document.querySelectorAll('.tab').forEach(tab => {
            tab.classList.remove('active');
        });

        // 显示选中的标签页内容
        document.getElementById(tabName + '-tab').classList.add('active');

        // 激活选中的标签
        event.target.classList.add('active');

        // 如果切换到文档管理标签页，加载文档列表
        if (tabName === 'docs') {
            loadDocumentList();
        }
    }

    // 文件拖拽处理
    function handleDragOver(event) {
        event.preventDefault();
        event.currentTarget.classList.add('dragover');
    }

    function handleDragLeave(event) {
        event.currentTarget.classList.remove('dragover');
    }

    function handleDrop(event) {
        event.preventDefault();
        event.currentTarget.classList.remove('dragover');

        const files = event.dataTransfer.files;
        if (files.length > 0) {
            uploadFile(files[0]);
        }
    }

    // 文件选择处理
    function handleFileSelect(event) {
        const file = event.target.files[0];
        if (file) {
            uploadFile(file);
        }
    }

    // 文件上传
    async function uploadFile(file) {
        if (isLoading) return;

        const formData = new FormData();
        formData.append('file', file);

        try {
            isLoading = true;
            showStatus('正在上传文件...', 'info');

            const response = await fetch('/api/swagger/upload', {
                method: 'POST',
                body: formData
            });

            const result = await response.json();
            console.log('上传响应结果：', result);
            if (result.success === true) {
                showStatus('文件上传成功！', 'success'); // ✅ 第二个参数传入 status 类型
                // 显示格式化输出
                if (result.formattedOutput) {
                    addMessage(result.formattedOutput, 'ai');
                    switchTab('chat');
                }
            } else {
                showStatus('上传失败：' + result.error, 'error');
            }
        } catch (error) {
            // showStatus('上传失败：' + error.message, 'error');
        } finally {
            isLoading = false;
        }
    }

    // URL 导入
    async function importFromUrl() {
        const url = document.getElementById('urlInput').value.trim();
        if (!url) {
            showStatus('请输入有效的 URL 地址', 'error');
            return;
        }

        if (isLoading) return;

        try {
            isLoading = true;
            showStatus('正在从 URL 导入文档...', 'info');

            const response = await fetch('/api/swagger/import-url', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({url: url})
            });

            const result = await response.json();

            if (result.success) {
                showStatus('文档导入成功！', 'success');
                document.getElementById('urlInput').value = '';
                // 显示格式化输出
                if (result.formattedOutput) {
                    addMessage(result.formattedOutput, 'ai');
                    switchTab('chat');
                }
            } else {
                showStatus('导入失败：' + result.error, 'error');
            }
        } catch (error) {
        } finally {
            isLoading = false;
        }
    }

    // 发送消息
    async function sendMessage() {
        const input = document.getElementById('messageInput');
        const message = input.value.trim();

        if (!message || isLoading) return;

        // 添加用户消息
        addMessage(message, 'user');
        input.value = '';

        // 设置加载状态
        isLoading = true;
        const sendBtn = document.getElementById('sendBtn');
        const sendIcon = document.getElementById('sendIcon');
        sendBtn.disabled = true;
        sendIcon.innerHTML = '<div class="loading"></div>';

        try {
            const response = await fetch('/api/chat/message', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({message: message})
            });

            const result = await response.json();

            if (result.success) {
                addMessage(result.message, 'ai');
            } else {
                addMessage('抱歉，处理消息时出现错误：' + result.error, 'ai');
            }
        } catch (error) {
            addMessage('抱歉，网络连接出现问题：' + error.message, 'ai');
        } finally {
            isLoading = false;
            sendBtn.disabled = false;
            sendIcon.innerHTML = '➤';
        }
    }

    // 添加消息到聊天区域
    function addMessage(content, type) {
        const messagesContainer = document.getElementById('chatMessages');
        const messageDiv = document.createElement('div');
        messageDiv.className = `message message-${type}`;

        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';

        // 处理换行和格式化
        const formattedContent = content
            .replace(/\n/g, '<br>')
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/`(.*?)`/g, '<code style="background: #f3f4f6; padding: 0.2rem 0.4rem; border-radius: 0.25rem; font-size: 0.8rem;">$1</code>');

        contentDiv.innerHTML = formattedContent;
        messageDiv.appendChild(contentDiv);
        messagesContainer.appendChild(messageDiv);

        // 滚动到底部
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    // 键盘事件处理
    function handleKeyDown(event) {
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault();
            sendMessage();
        }
    }

    // 显示状态消息
    function showStatus(message, type) {
        // 移除现有的状态消息
        const existingStatus = document.querySelector('.status');
        if (existingStatus) {
            existingStatus.remove();
        }

        const statusDiv = document.createElement('div');
        statusDiv.className = `status status-${type}`;
        statusDiv.textContent = message;

        // 添加到当前活跃的标签页
        const activeTab = document.querySelector('.tab-content.active');
        activeTab.insertBefore(statusDiv, activeTab.firstChild);

        // 3秒后自动移除成功消息
        if (type === 'success') {
            setTimeout(() => {
                if (statusDiv.parentNode) {
                    statusDiv.remove();
                }
            }, 3000);
        }
    }

    // 加载文档列表
    async function loadDocumentList() {
        const documentList = document.getElementById('documentList');
        documentList.innerHTML = '<div class="status status-info">正在加载文档列表...</div>';

        try {
            const response = await fetch('/api/swagger/status');
            const result = await response.json();

            if (result.totalDocuments === 0) {
                documentList.innerHTML = '<div class="status status-info">还没有上传任何文档。请先上传 OpenAPI/Swagger 文档。</div>';
                return;
            }

            let html = '';
            result.documents.forEach(doc => {
                const isActive = doc.id === result.activeDocumentId;
                html += `
                        <div class="document-item ${isActive ? 'active' : ''}" onclick="selectDocument('${doc.id}')">
                            <div class="document-title">${doc.title} ${isActive ? '(当前活跃)' : ''}</div>
                            <div class="document-meta">
                                版本: ${doc.version} |
                                接口: ${doc.pathCount} 个路径, ${doc.operationCount} 个操作 |
                                上传时间: ${new Date(doc.uploadTime).toLocaleString()}
                            </div>
                        </div>
                    `;
            });

            documentList.innerHTML = html;
        } catch (error) {
            documentList.innerHTML = '<div class="status status-error">加载文档列表失败：' + error.message + '</div>';
        }
    }

    // 选择文档
    function selectDocument(documentId) {
        addMessage(`切换到文档: ${documentId}`, 'user');
        addMessage(`正在切换到文档 ${documentId}...`, 'ai');
        switchTab('chat');
    }

    // 页面加载完成后的初始化
    document.addEventListener('DOMContentLoaded', function () {
        // 自动调整文本框高度
        const messageInput = document.getElementById('messageInput');
        messageInput.addEventListener('input', function () {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 128) + 'px';
        });

        // 检查服务状态
        checkServiceStatus();
    });

    // 检查服务状态
    async function checkServiceStatus() {
        try {
            const response = await fetch('/api/chat/status');
            const result = await response.json();

            if (!result.available) {
                addMessage('⚠️ AI 服务当前不可用，请检查配置。', 'ai');
            }
        } catch (error) {
            addMessage('⚠️ 无法连接到后端服务，请确保服务正在运行。', 'ai');
        }
    }
</script>
</body>
</html>

